<?php

class LoginController extends GTL_Action {

    public function init() {
	parent::init();
	$this->sessionName = Zend_Registry::get('sessionName');
	$auth = Zend_Auth::getInstance();
	$this->view->LoggedIn = $auth->hasIdentity();
	$defaultSession = new Zend_Session_Namespace($this->sessionName);
	$defaultSessionVal = $defaultSession->getIterator();
	if (isset($defaultSessionVal['storage'])
		&& !empty($defaultSessionVal['storage'])) {
	    $this->view->user = $defaultSessionVal['storage'];
	    $this->view->loggedinUserId = $this->view->user->usr_id;
	    $this->_helper->redirector('index', 'index', '');
	}
	/* Initialize action controller here */
    }

    public function indexAction() {
        
	$this->_helper->layout()->setLayout('login');
	$loginForm = new Form_LoginForm();
	$this->view->form = $loginForm;
	$errorMessage = Array();

	if ($this->_request->isPost()) {
	    $postedData = $this->_request->getPost();
	    if (!$loginForm->isValid($postedData)) {
		$errorMessage = $loginForm->getMessages();
	    } else {
		$auth = Zend_Auth::getInstance();
		$adapter = GTL_Common::getAuthAdapter($postedData, 'default');
		$result = $auth->authenticate($adapter);
		if ($result->isValid()) {
		    $auth->getStorage();
                    $objUser = $adapter->getResultRowObject();
                    //User is of the type Admin 
                    if ($objUser->lgn_type == '1') {
                        $adminObj = new Model_Admin();
                        $dataArray = Array();
                        $dataArray['lgn_id'] = $objUser->lgn_id;
                        $data = $adminObj->getAdminAuthData($dataArray);
                    } else if ($objUser->lgn_type == '2') {
                        //User is of the type Customer
                        $customerObj = new Model_Customer();
                        $dataArray = Array();
                        $dataArray['lgn_id'] = $objUser->lgn_id;
                        $data = $customerObj->getCustomerAuthData($dataArray);
                     } else if ($objUser->lgn_type == '3') {
                         //User is of the type Contractor
                        $contractorObj = new Model_Contractor();
                        $dataArray = Array();
                        $dataArray['lgn_id'] = $objUser->lgn_id;
                        $data = $contractorObj->getContractorAuthData($dataArray);
                    } else if ($objUser->lgn_type == '4') {
                        //User is of the type Designer
                        $designerObj = new Model_Designer();
                        $dataArray = Array();
                        $dataArray['lgn_id'] = $objUser->lgn_id;
                        $data = $designerObj->getDesignerAuthData($dataArray); 
                    }
		    $auth->setStorage(new Zend_Auth_Storage_Session($this->sessionName));
		    $auth->getStorage()->write($data);
		    $this->_helper->redirector('index', 'index', '');
		} else {
		    $loginForm->addErrorMessage("Username and Password do not match.");
		    $errorMessage['0'] = $loginForm->getErrorMessages();
		}
	    }
	}
	$this->view->errorMessage = $errorMessage;
    }

    public function forgotpasswordAction() {
	$this->_helper->layout()->setLayout('login');
	$frgtPwdForm = new Form_ForgotpasswordForm();
	$this->view->form = $frgtPwdForm;
	$errorMessage = Array();
	$successmessage = "";
	if ($this->_request->isPost()) {
	    $postedData = $this->_request->getPost();
	    if (!$frgtPwdForm->isValid($postedData)) {
		$errorMessage = $frgtPwdForm->getMessages();
	    } else {
		$model = new Model_Login();
		$usrArray = $model->checkEmailForForgotPassword($postedData['email']);
		if (empty($usrArray) || $usrArray['lgn_id'] == '') {
		    $frgtPwdForm->addErrorMessage("Email address is not registered.");
		    $errorMessage['0'] = $frgtPwdForm->getErrorMessages();
		} else {
		    $actualPassword = GTL_Common::generatePassword(9, 2);
		    $md5_password = md5($actualPassword);
		    $imgurl = $this->view->BASE_URL . "public/images/layout/logo.png";
		    $body = "
				<html>
				<head>
				</head>
				<body>
				<table style='width:50%'>
				    <tr>
					<td>
					    <p>
						<img src='" . $imgurl . "' height='90px' />
					    </p>
					</td>
				    </tr>
				    <tr>
				    <td>
				    <p>Hello user</p>
				    <p>New password for your " . $this->config->SITE_NAME . " admin!</p>
				    <table border='1' cellpadding='10'>
					    <tr>
						    <td>Email Address</td>
						    <td width='80px' align='center'>" . $usrArray['lgn_email'] . "</td>
					    </tr>
					    <tr>
						    <td>Password</td>
						    <td>" .  $actualPassword  . "</td>
					    </tr>
				    </table>
				    <p>
				    Thanks,<br/>
				    The Admin Team
				    </p>
				     </td>
				    </tr>
				</table>
				</body>
				</html>
				";
		    $mail = new Zend_Mail();
		    $mail->setBodyText($body);
		    $mail->setBodyHtml($body, "iso-8859-1");
                    $mail->addTo('wikitudedev@gmail.com', 'Master Admin');
                    $mail->setReplyTo('wikitudedev@gmail.com', 'Master Admin');
		    $mail->addTo($usrArray['lgn_email'], 'Admin User');
		    $mailSubject = "Forgot Password Request";
		    $mail->addHeader('MIME-Version', '1.0');
		    $mail->addHeader('Content-Transfer-Encoding', '8bit');
		    $mail->addHeader('X-Mailer:', 'PHP/' . phpversion());
		    $mail->setSubject($mailSubject);
		    try {
			$mail->send();
			$dataUpdate = array();
			$dataUpdate['lgn_id'] = $usrArray['lgn_id'];
			$dataUpdate['lgn_password'] = $md5_password;
			$model->save($dataUpdate, 'lgn_id');
			$frgtPwdForm->reset();
			$successmessage = "New password is sent to your email account.";
		    } catch (Zend_Exception $e) {
			$frgtPwdForm->addErrorMessage("Due to technical problem, email has not been sent. Please try later or contact webmaster.");
			$errorMessage['0'] = $frgtPwdForm->getErrorMessages();
		    }
		}
	    }
	}
	$this->view->successmessage = $successmessage;
	$this->view->errorMessage = $errorMessage;
    }

}

?>
